package com.ljq.collectionD;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * Description: 缓存url
 * Author: A
 * Date: 2025/2/26
 * Time: 15:41
 */
public class LRUCache {
    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(2); // 创建一个容量为 2 的 LRUCache
        lruCache.put(1, 1); // 添加键 1，值 1
        lruCache.put(2, 2); // 添加键 2，值 2
        lruCache.put(3, 3); // 添加键 3，值 3，键 2 被淘汰
        lruCache.put(4, 4); // 添加键 4，值 4，键 1 被淘汰
        lruCache.get(4);
        lruCache.displayCacheOrder();
    }
    private final int capacity;
    private final LinkedList<Integer> cache; // 维护顺序

    private final HashMap<Integer,Integer> map;  // 存储信息

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new LinkedList<>();
        this.map = new HashMap<>();
    }

    // 获取缓存中的值
    // 显示当前缓存的顺序
    public void displayCacheOrder() {
        System.out.print("当前缓存顺序: ");
        for (Integer key : cache) {
            System.out.print(key + " ");
        }
        System.out.println();
    }
    public int get(int key){
       if(!map.containsKey(key)){
           return  -1;
       }
       cache.remove((Integer) key);
        cache.addFirst(key);
        return map.get(key);
    }

    public  void show(){
        for (Integer integer : map.keySet()) {
            System.out.println(map.get(integer));
        }
    }
    public void put(int key, int value){
        if(map.containsKey(key)){
            map.put(key,value);
            cache.remove((Integer) key);
            cache.addFirst(key);
        } else {
            // 如果键不存在，检查缓存是否已满
            if(cache.size() >=capacity){
            Integer  lruKey =  cache.removeLast();
            map.remove(lruKey);
            }
            map.put(key,value);
            cache.addFirst(key);
        }
    }
}
